package com.wangbo.box.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * 迭代器模式
 * <p>
 * 提供一个对象来顺序访问聚合对象中的一系列数据，而不暴露聚合对象的内部表示。
 */
public class IteratorPattern {

    interface Iterator {
        Object first();

        Object next();

        boolean hasNext();
    }

    static class RealIterator implements Iterator {

        List<Object> list;
        int index = -1;

        public RealIterator(List<Object> list) {
            this.list = list;
        }

        @Override
        public Object first() {
            return list.get(0);
        }

        @Override
        public Object next() {
            return hasNext() ? list.get(++index) : null;
        }

        @Override
        public boolean hasNext() {
            return index < list.size() - 1;
        }
    }

    interface Aggregate {

        void add(Object o);

        void remove(Object o);

        Iterator getIterator();
    }

    static class RealAggregate implements Aggregate {

        private List<Object> list = new ArrayList<Object>();

        @Override
        public void add(Object o) {
            list.add(o);
        }

        @Override
        public void remove(Object o) {
            list.remove(o);
        }

        @Override
        public Iterator getIterator() {
            return new RealIterator(list);
        }
    }

    public static void main(String[] args) {
        Aggregate aggregate = new RealAggregate();
        aggregate.add("123");
        aggregate.add("asd");
        aggregate.add("bnm");
        Iterator iterator = aggregate.getIterator();
        while (iterator.hasNext()){
            Object next = iterator.next();
            System.out.println(next);
        }
    }
}
